package com.jiantong.web.open.app.insurance;

import com.jiantong.user.model.BreedFactory;

import com.jiantong.user.service.BreedFactoryReadService;

import com.jiantong.work.dto.ClaimsSettementAllDto;
import com.jiantong.work.model.ImmunizationSubRecord;
import com.jiantong.work.model.ProductionReport;
import com.jiantong.work.model.yangzhibaoxian.*;
import com.jiantong.work.service.ImmunizationRecordReadService;
import com.jiantong.work.service.ImmunizationSubRecordReadService;
import com.jiantong.work.service.ProductionReportReadService;
import com.jiantong.work.service.yangzhibaoxian.*;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.Paging;
import io.terminus.common.model.Response;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPException;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.naming.OperationNotSupportedException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static io.terminus.msg.util.JsonUtil.JSON;

/**
 * Created by ThinkPad on 2017/9/8.
 */
@Slf4j
@OpenBean
public class ClaimsSettlementApis {

    @RpcConsumer
    private ClaimsSettlementService claimsSettlementService;
    @RpcConsumer
    private ClaimsLossService claimsLossService;
    @RpcConsumer
    private HarmlessConductService harmlessConductService;
    @RpcConsumer
    private ClaimsResultService claimsResultService;
    @RpcConsumer
    private BankcardService bankcardService;
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;
    @RpcConsumer
    private InsuranceAreaService insuranceAreaService;
    @RpcConsumer
    private FileService fileService;
    @RpcConsumer
    private InformService informService;
    @RpcConsumer
    private ImmunizationRecordReadService immunizationRecordReadService;
    @RpcConsumer
    private ImmunizationSubRecordReadService immunizationSubRecordReadService;
    @RpcConsumer
    private ProductionReportReadService productionReportReadService;
    @RpcConsumer
    private InsuranceApplicationService insuranceApplicationService;
    @RpcConsumer
    private InsuranceRetailService insuranceRetailService;

    /**
     * 创建理赔单
     *
     * @param claimsSettlement
     * @return
     */
    @OpenMethod(
            key = "insurance.create.ClaimsSettlement",
            paramNames = {"claimsSettlement"},
            httpMethods = RequestMethod.POST
    )
    public Long createClaimsSettlement(ClaimsSettlement claimsSettlement) {

        BreedFactory breedFactory = breedFactoryReadService.findById(claimsSettlement.getBreed_factory_id()).getResult();
        //市
        String cityID = breedFactory.getCityId().toString();
        if (cityID.length() == 1) {
            cityID = "0" + cityID;
        }
        //县
        String regionID = breedFactory.getRegionId().toString();
        if (regionID.length() == 1) {
            regionID = "0" + regionID;
        }
        // 镇
        String streetId = null;
        if (breedFactory.getStreetId() == null) {
            streetId = "000";
        } else {
            streetId = breedFactory.getStreetId().toString();
        }

        if (streetId.length() == 1) {
            streetId = "00" + streetId;
        }
        if (streetId.length() == 2) {
            streetId = "0" + streetId;
        }
        //村

        String villageId = null;
        if (breedFactory.getVillageId() == null) {
            villageId = "000";
        } else {
            villageId = breedFactory.getVillageId().toString();
        }

        if (villageId.length() == 1) {
            villageId = "00" + villageId;
        }
        if (villageId.length() == 2) {
            villageId = "0" + villageId;
        }
        String area = breedFactory.getProvinceId().toString()
                + cityID
                + regionID
                + streetId
                + villageId;

        InsuranceArea insuranceArea = insuranceAreaService.findByAreaCode(area);
        Long receiver_id = -1L;
        String receiver_name = null;
        if (insuranceArea != null) {
            receiver_id = insuranceArea.getUser_id();
            receiver_name = insuranceArea.getUser_name();
        }

        claimsSettlement.setReceiver_id(receiver_id);
        claimsSettlement.setReceiver_name(receiver_name);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
        String number = sdf.format(new Date());
        claimsSettlement.setNumber("CLA" + number);
        claimsSettlement.setCheck_status(0);
        Map map = new HashMap();
        map.put("insured_breed_id", claimsSettlement.getBreed_factory_id());
        List<ClaimsResult> claimsResultList = claimsResultService.list(map).getResult();
        Double money = 0.00;
        if (claimsResultList.size() != 0) {
            for (ClaimsResult claimsResult : claimsResultList) {
                money += claimsResult.getPay_money();
            }
        }

        claimsSettlement.setClaims_money(money);
        claimsSettlement.setClaims_count(claimsResultList.size());
        return claimsSettlementService.create(claimsSettlement);
    }

    /**
     * 修改理赔单据
     * @param id
     * @param check_status
     * @return
     */
    @OpenMethod(
            key = "insurance.update.updateClaims",
            paramNames = {"id", "check_status"},
            httpMethods = RequestMethod.POST
    )
    public Boolean updateClaims(Long id, int check_status) {

        ClaimsSettlement claimsSettlement = claimsSettlementService.findById(id).getResult();
        claimsSettlement.setCheck_status(check_status);
        return claimsSettlementService.update(claimsSettlement);
    }

    /**
     * 根据id查询理赔单
     *
     * @param id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.ClaimsSettlementByID",
            paramNames = {"id"},
            httpMethods = RequestMethod.POST
    )
    public ClaimsSettlement claimsSettlementByID(Long id) {
        return claimsSettlementService.findById(id).getResult();
    }

    /**
     * 养殖端查询理赔单据(一年内)
     *
     * @param breed_factory_id
     * @param check_status
     * @return
     */
    @OpenMethod(
            key = "insurance.select.ClaimsSettlementByFactory",
            paramNames = {"breed_factory_id", "check_status"},
            httpMethods = RequestMethod.POST
    )
    public List<ClaimsSettlement> claimsSettlements(Long breed_factory_id, List check_status) {
        Map map = new HashMap();
        Calendar now = Calendar.getInstance();
        map.put("breed_factory_id", breed_factory_id);
        map.put("Liststatus", check_status);
        map.put("year", now.get(Calendar.YEAR));

        return claimsSettlementService.list(map).getResult();
    }

    /**
     * 更新理赔单据
     *
     * @param claimsSettlement
     * @return
     */
    @OpenMethod(
            key = "insurance.update.ClaimsSettlement",
            paramNames = {"claimsSettlement"},
            httpMethods = RequestMethod.POST
    )
    public Boolean updateClaimsSettlement(ClaimsSettlement claimsSettlement) {

        return claimsSettlementService.update(claimsSettlement);
    }

    /**
     * 保险端  查看理赔单据（list）
     * 0已提交1初审通过2初审未通过3已勘察4审核通过5审核不通过
     *
     * @param receiver_id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.claimsSettlementList",
            paramNames = {"receiver_id", "check_status", "pageNo", "pageSize"},
            httpMethods = RequestMethod.POST
    )
    public Paging<ClaimsSettlement> claimsSettlementList(Long receiver_id, List check_status, int pageNo, int pageSize) {
        Map map = new HashMap();
        map.put("Liststatus", check_status);
        map.put("receiver_id", receiver_id);
        return claimsSettlementService.ping(pageNo, pageSize, map).getResult();
    }


    /**
     * 创建定损表
     *
     * @param mapList              claimsLoss（list）定损表多个
     * @param claims_settlement_id 理赔单id
     * @param files(无害化照片和定损照片)
     * @param harmlessConduct
     * @return
     */

    @OpenMethod(
            key = "insurance.create.claimsLoss",
            paramNames = {"mapList", "claims_settlement_id", "files", "harmlessConduct"},
            httpMethods = RequestMethod.POST
    )
    @Transactional
    public Integer createClaimsLoss(List<Map> mapList, Long claims_settlement_id, List<Map> files, HarmlessConduct harmlessConduct) throws ParseException {
        List<ClaimsLoss> claimsLossList = new ArrayList<>();
        for (Map map : mapList) {
            ClaimsLoss claimsLoss = new ClaimsLoss();
            Integer claims_settlement_id1 = (int) map.get("claims_settlement_id");
            claimsLoss.setClaims_settlement_id(claims_settlement_id1.longValue());
            claimsLoss.setEar_number((String) map.get("ear_number"));
            claimsLoss.setAge((int) map.get("age"));

            claimsLoss.setLength(Double.parseDouble((String) map.get("length")));
            claimsLoss.setWeight(Double.parseDouble((String) map.get("weight")));
            claimsLoss.setUnit_money(Double.parseDouble((String) map.get("unit_money")));
            claimsLoss.setRated_money(Double.parseDouble((String) map.get("rated_money")));
            claimsLoss.setNotes((String) map.get("notes"));
            claimsLoss.setSign_description((String) map.get("sign_description"));
            claimsLoss.setDeath_cause((String) map.get("death_cause"));
            claimsLoss.setImmune((String) map.get("immune"));
            Object obj = map.get("prospect_date");
            Date date = new Date();
            if (obj instanceof char[] || obj instanceof String) date = DateTime.parse((String) obj).toDate();

            if (obj instanceof Date) date = (Date) obj;

            claimsLoss.setProspect_date(date);
            claimsLoss.setProspect_type((int) map.get("prospect_type"));
            claimsLoss.setStock((int) map.get("stock"));
            claimsLoss.setInsured_count((int) map.get("insured_count"));
            claimsLoss.setDeath_count((int) map.get("death_count"));
            claimsLoss.setLongitude((String) map.get("longitude"));
            claimsLoss.setLatitude((String) map.get("latitude"));
            claimsLoss.setQuarantineNumber((String) map.get("quarantineNumber"));
            claimsLossList.add(claimsLoss);

        }
        ClaimsSettlement claimsSettlement = claimsSettlementService.findById(claims_settlement_id).getResult();
        claimsSettlement.setCheck_status(3);
        createFile(files);
        createHarmlessConduct(harmlessConduct);
        claimsSettlementService.update(claimsSettlement);
        return claimsLossService.creates(claimsLossList);
    }

    /**
     * 根据理赔单id查询详细信息（单据，理赔结果，无害化，图片，定损情况）
     *
     * @param claims_settlement_id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.claimsSettementAllDto",
            paramNames = {"claims_settlement_id"},
            httpMethods = RequestMethod.POST
    )
    public ClaimsSettementAllDto claimsSettementAllDto(Long claims_settlement_id) {
        ClaimsSettementAllDto claimsSettementAllDto = new ClaimsSettementAllDto();
        ClaimsSettlement claimsSettlement = claimsSettlementService.findById(claims_settlement_id).getResult();
        Map map = new HashMap();
        map.put("relevance_id", claims_settlement_id);
        List<Integer> integerList = new ArrayList<>();
        integerList.add(2);
        integerList.add(3);
        map.put("title", integerList);
        List<File> fileList = fileService.list(map).getResult();
        map.put("claims_settlement_id", claims_settlement_id);
        List<ClaimsLoss> claimsLossList = claimsLossService.list(map).getResult();
        ClaimsResult claimsResult = claimsResultService.findByClaimsId(claims_settlement_id);
        HarmlessConduct harmlessConduct = harmlessConductService.findByClaimsId(claims_settlement_id);

        claimsSettementAllDto.setFileList(fileList);
        claimsSettementAllDto.setClaimsLossList(claimsLossList);
        claimsSettementAllDto.setClaimsResult(claimsResult);
        claimsSettementAllDto.setHarmlessConduct(harmlessConduct);
        claimsSettementAllDto.setClaimsSettlement(claimsSettlement);
        return claimsSettementAllDto;

    }

    /**
     * 根据理赔单id查询定损表（list）
     *
     * @param claims_settlement_id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.claimsLossList",
            paramNames = {"claims_settlement_id"},
            httpMethods = RequestMethod.POST
    )
    public List<ClaimsLoss> claimsLossList(Long claims_settlement_id) {

        Map map = new HashMap();
        map.put("claims_settlement_id", claims_settlement_id);
        List<ClaimsLoss> claimsLossList = claimsLossService.list(map).getResult();
        return claimsLossList;
    }

    /**
     * 创建无害化单据
     *
     * @param harmlessConduct
     * @return
     */
    @OpenMethod(
            key = "insurance.create.harmlessConduct",
            paramNames = {"harmlessConduct"},
            httpMethods = RequestMethod.POST
    )
    public Long createHarmlessConduct(HarmlessConduct harmlessConduct) {
        return harmlessConductService.create(harmlessConduct);
    }

    /**
     * 根据理赔单id查看无害化单据（list）
     *
     * @param claims_settlement_id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.harmlessConductList",
            paramNames = {"claims_settlement_id"},
            httpMethods = RequestMethod.POST
    )
    public List<HarmlessConduct> harmlessConductList(Long claims_settlement_id) {
        Map map = new HashMap();
        map.put("claims_settlement_id", claims_settlement_id);
        List<HarmlessConduct> harmlessConductList = harmlessConductService.list(map).getResult();
        return harmlessConductList;
    }

    /**
     * 创建理赔结果单据
     *
     * @param claimsResult
     * @return
     */
    @OpenMethod(
            key = "insurance.create.claimsResult",
            paramNames = {"claimsResult", "check_status"},
            httpMethods = RequestMethod.POST
    )
    @Transactional
    public Long createClaimsResult(ClaimsResult claimsResult, int check_status) {
        ClaimsSettlement claimsSettlement = claimsSettlementService.findById(claimsResult.getClaims_settlement_id()).getResult();
        claimsSettlement.setCheck_status(check_status);
        claimsSettlementService.update(claimsSettlement);
        return claimsResultService.create(claimsResult);
    }

    /**
     * 根据理赔单id查询理赔结果（list）
     *
     * @param claims_settlement_id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.claimsResultList",
            paramNames = {"claims_settlement_id"},
            httpMethods = RequestMethod.POST
    )
    public List<ClaimsResult> claimsResultList(Long claims_settlement_id) {
        Map map = new HashMap();
        map.put("claims_settlement_id", claims_settlement_id);

        List<ClaimsResult> claimsResultList = claimsResultService.list(map).getResult();
        return claimsResultList;
    }

    /**
     * 添加养殖户银行卡
     *
     * @param bankcard
     * @return
     */
    @OpenMethod(
            key = "insurance.create.Bankcard",
            paramNames = {"bankcard"},
            httpMethods = RequestMethod.POST
    )
    public Long createBankcard(Bankcard bankcard) {
        return bankcardService.create(bankcard);

    }

    /**
     * 查询用户拥有的银行卡
     *
     * @param user_id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.bankcardList",
            paramNames = {"user_id"},
            httpMethods = RequestMethod.POST
    )
    public List<Bankcard> bankcardList(Long user_id) {

        Map map = new HashMap();
        map.put("user_id", user_id);
        return bankcardService.list(map).getResult();
    }

    /**
     * 创建文件表
     *
     * @param files
     * @return
     */
    @OpenMethod(
            key = "insurance.create.file",
            paramNames = {"files"},
            httpMethods = RequestMethod.POST
    )
    @Transactional
    public Integer createFile(List<Map> files) {
        List<File> fileList = new ArrayList<>();
        for (Map map : files) {
            File file = new File();
            file.setType1((int) map.get("type1"));
            file.setType2((int) map.get("type2"));
            Integer relevance_id = (int) map.get("relevance_id");
            file.setRelevance_id(relevance_id.longValue());
            file.setAddress((String) map.get("address"));
            file.setState((String) map.get("state"));
            fileList.add(file);

        }

        return fileService.creates(fileList);


    }

    /**
     * 根据类型查询图片
     *
     * @param type1
     * @param type2
     * @param relevance_id
     * @return
     */
    @OpenMethod(
            key = "insurance.select.fileList",
            paramNames = {"type1", "type2", "relevance_id"},
            httpMethods = RequestMethod.POST
    )
    public List<File> fileList(int type1, int type2, Long relevance_id) {
        Map map = new HashMap();
        map.put("type1", type1);
        map.put("type2", type2);
        map.put("relevance_id", relevance_id);
        return fileService.list(map).getResult();
    }

    /**
     * 保险端 养殖免疫生产信息
     *
     * @param breedId(养殖场id)
     * @return
     */
    @OpenMethod(
            key = "insurance.select.BreedFactoryData",
            paramNames = {"breedId"},
            httpMethods = RequestMethod.POST
    )
    public Map BreedFactoryData(Long breedId) {
        BreedFactory breedFactory = breedFactoryReadService.findById(breedId).getResult();
        int breeType = breedFactory.getBreedType();
        int stockQuantity = breedFactory.getStockQuantity();
        int immunizationStatus = -1;
        Date date = null;
        Map map = new HashMap();
        map.put("breedFactoryId", breedId);
        map.put("deleteFlag", 1);
        Long immTimes = immunizationSubRecordReadService.countISRTimes(map);
        if (immTimes != 0L) {
            immunizationStatus = 1;
        }
        List<ImmunizationSubRecord> immunizationSubRecordList = immunizationSubRecordReadService.findBybreedFactoryId(breedId);
        if (immunizationSubRecordList.size() != 0) {
            date = immunizationSubRecordList.get(0).getDate();
        }
        int prostatus = -1;
        Date date1 = null;
        List<ProductionReport> productionReportList = productionReportReadService.pagingProductionReport(1, 100000, 1, breedId).getResult().getData();
        if (productionReportList.size() != 0) {
            prostatus = 1;
            date1 = productionReportList.get(0).getDate();
        }
        Map map1 = new HashMap();
        map1.put("insured_breed_id", breedId);
        map1.put("check_status", 4);
        map1.put("breed_factory_id", breedId);
        List<Long> longs = new ArrayList<>();
        longs.add(-1L);
        List<InsuranceApplication> insuranceApplicationList = insuranceApplicationService.list(map1).getResult();

        List<InsuranceRetail> insuranceRetailServiceList = insuranceRetailService.list(map1).getResult();
        if (insuranceRetailServiceList.size() != 0) {
            for (InsuranceRetail insuranceRetail : insuranceRetailServiceList) {
                longs.add(insuranceRetail.getApplication_id());
            }
        }
        Map ids = new HashMap();
        ids.put("ids", longs);
        List<InsuranceApplication> insuranceApplications = insuranceApplicationService.findByIds(longs).getResult();

        insuranceApplicationList.addAll(insuranceApplications);

        Map data = new HashMap();
        data.put("breedType", breeType);//畜种
        data.put("stockQuantity", stockQuantity);//存栏
        data.put("immunizationStatus", immunizationStatus == 1 ? "是" : "否");//免疫状态
        data.put("immTimes", immTimes);//免疫次数
        data.put("immDate", date);//免疫日期
        data.put("proStatus", prostatus == 1 ? "是" : "否");//生产状态
        data.put("proDate", date1);//生产日期
        data.put("insuranceApplicationList", insuranceApplicationList);//历史保单

        return data;


    }


}
